//
//  FilterRowTemplate.m
//  Task Views
//
//  Created by Chris Karr on 2/26/09.
//  Copyright 2009 Chris J. Karr. All rights reserved.
//

#import "FilterRowTemplate.h"

@implementation FilterRowTemplate

- (double) matchForPredicate:(NSPredicate *) predicate
{
	if ([predicate isKindOfClass:[NSComparisonPredicate class]])
		return 1.0;
	
	return [super matchForPredicate:predicate];
}

- (NSArray *) displayableSubpredicatesOfPredicate:(NSPredicate *) predicate
{
	return nil;
}

- (void) setPredicate:(NSPredicate *) predicate
{
	NSArray * views = [self templateViews];
	
	if (predicate == nil)
	{
		[((NSPopUpButton *) [views objectAtIndex:0]) selectItemAtIndex:0];
		[((NSPopUpButton *) [views objectAtIndex:1]) selectItemAtIndex:0];
	}
	else
	{
		NSComparisonPredicate * comp = (NSComparisonPredicate *) predicate;

		NSString * left = [[comp leftExpression] keyPath];
		
		if ([((NSPopUpButton *) [views objectAtIndex:0]) numberOfItems] > 1)
			[((NSPopUpButton *) [views objectAtIndex:0]) selectItemWithTitle:left];
		else
			[((NSPopUpButton *) [views objectAtIndex:0]) selectItemAtIndex:0];
		
		NSPredicateOperatorType operator = [comp predicateOperatorType];
		
		NSArray * operators = [self operators];
		
		NSInteger index = [operators indexOfObject:[NSNumber numberWithInteger:operator]];
		
		[((NSPopUpButton *) [views objectAtIndex:1]) selectItemAtIndex:index];
		
		NSString * right = @"";

		if (predicate != nil)
		{
			NSMutableString * query = [NSMutableString stringWithString:[[comp rightExpression] description]];
			
			if ([query hasPrefix:@"\""])
				[query replaceCharactersInRange:NSMakeRange(0, 1) withString:@""];

			if ([query hasSuffix:@"\""])
				[query replaceCharactersInRange:NSMakeRange([query length] - 1 , 1) withString:@""];
			
			right = query;
		}

		[((NSTextField *) [views objectAtIndex:2]) setObjectValue:right];
	}
}

@end
